﻿namespace TCommon.Extension;

public static class StringExtension
{
    /// <summary>
    /// 字符串转16进制字节数组
    /// </summary>
    /// <param name="hexString">十六进制字符串</param>
    /// <returns></returns>
    // ReSharper disable once UnusedMember.Local
    public static OperateResult<byte[]> ToBytesFromHexString(this string hexString) 
    { 
        if (string.IsNullOrEmpty(hexString))
        {
            return OperateResult.CreateFailedResult<byte[]>("输入字符串为空");
        }

        hexString = hexString.Replace("0x", "");
        hexString = hexString.Replace("0X", "");
        hexString = hexString.Replace(" ", ""); 
        if ((hexString.Length % 2) != 0) 
            hexString += " "; 
        byte[] returnBytes = new byte[hexString.Length / 2]; 
        for (int i = 0; i < returnBytes.Length; i++) 
            returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
        return OperateResult.CreateSuccessResult(returnBytes);
    } 
}